package com.bailing.smstimerbutton;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

/**
 * Desc:   短信验证码倒计时按钮
 * Creator ling
 * Date:   2017/12/15 0015 17:15
 */

public class TimerButton extends AppCompatButton implements View.OnClickListener {

    private CountDownTimer countDownTimer;
    private OnClickListener mOnClickListener;

    private final int DEFAULT_COUNT_SECOND = 60;
    /**
     * 倒计时总时长，默认为60s
     */
    private long countSeconds = DEFAULT_COUNT_SECOND;

    /**
     * 初始文本
     */
    private String normalText;
    /**
     * 倒计时文本,需传入格式化字符串
     */
    private String timerText;
    /**
     * 重新获取文本
     */
    private String againText;

    /**
     * Enable 状态下背景图片
     */
    private Drawable enableBg;

    /**
     * 非 Enable 装态下背景图片
     */
    private Drawable unEnableBg;

    /**
     * Enable 状态下背景颜色
     */
    private int enableBgColor;

    /**
     * 非 Enable 装态下背景颜色
     */
    private int unEnableBgColor;

    /**
     * Enable 状态下背景
     */
    private int enableTextColor;

    /**
     * 非 Enable 装态下背景
     */
    private int unEnableTextColor;

    /**
     * 是否自动倒计时，true：自动， false:手动
     */
    private boolean autoStart;

    public TimerButton(Context context) {
        this(context, null);
    }

    public TimerButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TimerButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a =
            context.obtainStyledAttributes(attrs, R.styleable.TimerButton, defStyleAttr, 0);

        if (a != null) {
            countSeconds = a.getInteger(R.styleable.TimerButton_countSeconds, DEFAULT_COUNT_SECOND);

            normalText = a.getString(R.styleable.TimerButton_normalText);
            timerText = a.getString(R.styleable.TimerButton_timerText);
            againText = a.getString(R.styleable.TimerButton_againText);

            Drawable background = getBackground();
            if (background == null) {
                enableBg = a.getDrawable(R.styleable.TimerButton_enableBg);
                unEnableBg = a.getDrawable(R.styleable.TimerButton_unEnableBg);

                // 此处需要判断，否则如果 enablebg != null 时，会报错
                if (enableBg == null) {
                    enableBgColor = a.getColor(R.styleable.TimerButton_enableBg, Color.WHITE);
                }
                if (unEnableBg == null) {
                    unEnableBgColor = a.getColor(R.styleable.TimerButton_unEnableBg, Color.WHITE);
                }
            }

            enableTextColor = a.getColor(R.styleable.TimerButton_enableTextColor, Color.BLACK);
            unEnableTextColor = a.getColor(R.styleable.TimerButton_unEnableTextColor, Color.GRAY);

            autoStart = a.getBoolean(R.styleable.TimerButton_autoStart, false);
            a.recycle();
        }

        if (TextUtils.isEmpty(normalText)) normalText = "";
        if (TextUtils.isEmpty(timerText)) timerText = "";
        if (TextUtils.isEmpty(againText)) againText = "";
        setText(normalText);

        update(isEnabled());

        setOnClickListener(this);

        if (autoStart) {
            start();
        }
    }

    @Override
    public void onClick(View v) {
        // 开始倒计时
        start();
    }

    public interface OnClickListener {
        void onGetVerifyCode(View v);
    }

    public TimerButton setOnClickListener(OnClickListener listener) {
        mOnClickListener = listener;
        return this;
    }

    public TimerButton setCountSeconds(long countSeconds) {
        this.countSeconds = countSeconds;
        return this;
    }

    public TimerButton setNormalText(String normalText) {
        if (TextUtils.isEmpty(normalText)) normalText = "";
        this.normalText = normalText;
        return this;
    }

    public TimerButton setTimerText(String timerText) {
        if (TextUtils.isEmpty(timerText)) timerText = "";
        this.timerText = timerText;
        return this;
    }

    public TimerButton setAgainText(String againText) {
        if (TextUtils.isEmpty(againText)) againText = "";
        this.againText = againText;
        return this;
    }

    public void setEnableBg(Drawable enableBg) {
        this.enableBg = enableBg;
    }

    public void setUnEnableBg(Drawable unEnableBg) {
        this.unEnableBg = unEnableBg;
    }

    public void setEnableBgColor(int enableBgColor) {
        this.enableBgColor = enableBgColor;
    }

    public void setUnEnableBgColor(int unEnableBgColor) {
        this.unEnableBgColor = unEnableBgColor;
    }

    public void setEnableTextColor(int enableTextColor) {
        this.enableTextColor = enableTextColor;
    }

    public void setUnEnableTextColor(int unEnableTextColor) {
        this.unEnableTextColor = unEnableTextColor;
    }

    /**
     * 开启倒计时
     */
    private void start() {
        if (mOnClickListener != null) {
            // 获取验证码
            mOnClickListener.onGetVerifyCode(this);
        }

        setEnabled(false);
        countDownTimer = new CountDownTimer((countSeconds + 1) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long showTime = millisUntilFinished / 1000;
                // 一般来说，倒计时文字 是一串文字，这里使用格式化字符串
                setText(String.format(timerText, showTime));
            }

            @Override
            public void onFinish() {
                resetButton();
            }
        };
        countDownTimer.start();

        update(isEnabled());
    }

    /**
     * 停止倒计时
     */
    public void stop() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        resetButton();
    }

    private void resetButton() {
        setEnabled(true);
        setText(againText);
        update(isEnabled());
    }

    private void update(boolean isEnable) {

        if (isEnable) {
            if (enableBg != null) {
                setBackgroundDrawable(enableBg);
            }

            if (enableBgColor != 0) {
                setBackgroundColor(enableBgColor);
            }

            if (enableTextColor != 0) {
                setTextColor(enableTextColor);
            }
        } else {
            if (unEnableBg != null) {
                setBackgroundDrawable(unEnableBg);
            }

            if (unEnableBgColor != 0) {
                setBackgroundColor(unEnableBgColor);
            }

            if (unEnableTextColor != 0) {
                setTextColor(unEnableTextColor);
            }
        }
    }
}
